import { JsonController, Get, QueryParam } from 'routing-controllers';
import { UserService } from '../service/user.service';
import { sign, checkValid } from '../utils/auth';
import { Code } from '../utils/code';
import { Result } from '../utils/result';
import { Service, Inject } from 'typedi';

@Service()
@JsonController('/token')
export class TokenController {
  @Inject()
  userService: UserService;

  @Get('/get')
  async get(@QueryParam('id') id: string) {}

  @Get('/refresh')
  async refresh(@QueryParam('refresh_token') refreshToken: string) {
    const valid = checkValid(refreshToken);
    if (!valid.pass) {
      return Result.fail(Code.ERROR, `${valid.message} 请重新登录`);
    }
    const payload = { id: valid.payload.id, username: valid.payload.username };
    const access_token = sign(payload);
    const refresh_token = sign(payload, { expiresIn: '7d' });
    return Result.ok(Code.SUCCESS, '刷新成功', { access_token, refresh_token });
  }
}
